package org.example.chat;

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    // 服务器套接字，用于监听客户端连接
    private ServerSocket serverSocket;
    // 存储所有客户端处理器的集合
    private Set<ClientHandler> clientHandlers = new HashSet<>();
    // 存储用户头像映射关系
    private Map<String, String> userAvatars = new HashMap<>();

    public ChatServer(int port) throws IOException {
        // 步骤1：创建服务器套接字并绑定到指定端口
        serverSocket = new ServerSocket(port);
    }

    public void start() {
        System.out.println("服务器已启动，等待客户端连接...");
        while (true) {
            try {
                // 步骤3：将套接字设为监听模式，等待客户端连接
                // 步骤4：当有客户端请求时，接受连接并返回新的套接字
                Socket clientSocket = serverSocket.accept();
                // 为每个客户端创建一个新的处理线程
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                clientHandlers.add(clientHandler);
                clientHandler.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 内部类：处理每个客户端连接的线程
    private class ClientHandler extends Thread {
        private Socket clientSocket;  // 与客户端通信的套接字
        private PrintWriter out;      // 输出流，用于向客户端发送数据
        private BufferedReader in;    // 输入流，用于接收客户端数据
        private String username;
        private String avatar;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        public void run() {
            try {
                // 步骤5：创建输入输出流，用于与客户端通信
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                String inputLine;
                // 持续读取客户端发送的消息
                while ((inputLine = in.readLine()) != null) {
                    if (inputLine.startsWith("LOGIN:")) {
                        // 处理登录消息
                        String[] parts = inputLine.substring(6).split(":");
                        username = parts[0];
                        avatar = parts[1];
                        userAvatars.put(username, avatar);
                        
                        // 向新用户发送现有用户信息
                        for (Map.Entry<String, String> entry : userAvatars.entrySet()) {
                            if (!entry.getKey().equals(username)) {
                                out.println("USER:" + entry.getKey() + ":" + entry.getValue());
                            }
                        }
                        
                        // 广播新用户登录消息
                        broadcastMessage("LOGIN:" + username + ":" + avatar);
                    } else {
                        // 处理普通消息
                        System.out.println("收到客户端消息: " + inputLine);
                        broadcastMessage(inputLine);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 步骤7：关闭套接字和流
                    if (username != null) {
                        userAvatars.remove(username);
                        broadcastMessage("SYSTEM:" + username + " 离开了聊天室");
                    }
                    in.close();
                    out.close();
                    clientSocket.close();
                    clientHandlers.remove(this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 广播消息给所有连接的客户端
        private void broadcastMessage(String message) {
            for (ClientHandler handler : clientHandlers) {
                handler.out.println(message);
            }
        }
    }

    public static void main(String[] args) {
        int port = 12345;
        try {
            ChatServer server = new ChatServer(port);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 